<template>
  <n-drawer
    v-model:show="modelValue.toEdit"
    :width="502"
    :height="500"
    :placement="'bottom'"
  >
    <n-drawer-content
      :title="toADDFlag ? '添加' : '修改'"
      closable
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        :size="'medium'"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        :style="{ maxWidth: '640px' }"
      >
        <n-form-item
          label="开始时间"
          path="startTime"
        >
          <n-time-picker v-model:value="formValue.startTime" />
        </n-form-item>
        <n-form-item
          label="结束时间"
          path="endTime"
        >
          <n-time-picker v-model:value="formValue.endTime" />
        </n-form-item>
        <n-form-item
          label="描述"
          path="desc"
        >
          <n-input
            v-model:value="formValue.desc"
            placeholder="输入描述"
          />
        </n-form-item>
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick"
          >
            {{ toADDFlag ? "添加" : "修改" }}
          </n-button>
        </n-form-item>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup generic="T extends object & { toEdit: boolean,toDelete:boolean,toDealRowId: number|undefined}">
//  <n-time-picker v-model:value="formValue.startTime"/>
// <n-time-picker :default-value="1183135260000" />
// <n-time-picker v-model:value="formValue.endTime" />
import type { LifeModel } from "@model/lifeModel";
import type { SurfaceSetting } from "@model/surfaceSetting";
import type { TimeManageList } from "@model/timeManage";
import { TimeManage } from "@model/timeManage";
import UseLifeModel from "@pinias/UseLifeModel";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import UseTimeManageList from "@pinias/UseTimeManageList";
import pinia from "@pinias/pinia";
import {
  NTimePicker,
  NForm,
  NFormItem,
  NInput,
  NDrawer,
  NDrawerContent,
  NButton,
  FormInst,
  useMessage,
} from "naive-ui";
import { ref, computed, watch } from "vue";

// 全局数据
const { getLifeModel } = UseLifeModel(pinia);
const lifeModel: LifeModel = getLifeModel();
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();
const { getTimeManageList } = UseTimeManageList(pinia);
const timeManageList: TimeManageList = getTimeManageList();

// 父组件数据
const props = defineProps<{ modelValue: T }>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});

// 页面数据
const toADDFlag = computed(() => {
  return typeof modelValue.value.toDealRowId == "undefined";
});
const rules = {
  startTime: {
    type: "number",
    required: true,
    message: "请输入开始时间",
    trigger: ["blur", "change"],
  },
  endTime: {
    type: "number",
    required: true,
    message: "请输入结束时间",
    trigger: ["blur", "change"],
  },
  desc: {
    required: true,
    message: "请输入描述",
    trigger: ["input"],
  },
};
const formRef = ref<FormInst | null>(null);
const getNewFormValue = () => {
  // console.log('getNewFormValue',toDealItem);
  const nullModel = {
    id: surfaceSetting.maxId,
    startTime: new Date().getTime(),
    endTime: new Date().getTime(),
    desc: "",
  };
  if (toADDFlag.value) return nullModel;
  else {
    const toDealRow = timeManageList.getTimeManageById(modelValue.value.toDealRowId);
    if (toDealRow === undefined) {
      return nullModel;
    } else
      return {
        id: toDealRow?.id,
        startTime: toDealRow?.startTime,
        endTime: toDealRow?.endTime,
        desc: toDealRow?.desc,
      };
  }
};
const formValue = ref(getNewFormValue());
watch(modelValue.value, () => {
  // console.log('formValue',formValue);
  formValue.value = getNewFormValue();
  // console.log('formValue2',formValue);
});
const message = useMessage();
const addNewOne = () => {
  const tosave = formValue.value;
  // console.log('tosave',tosave)
  const lifeModelData = lifeModel.getLifeModelDataById(surfaceSetting.showLifeModel);
  if (lifeModelData === undefined) {
    message.error("生活模式未选择");
    return;
  }
  const list = lifeModelData?.timeManageList;
  // console.log('toDealRow list',list)
  // console.log('formValue data',data)
  if (toADDFlag.value) {
    list?.push(tosave.id);
    timeManageList.addTimeManage(
      new TimeManage(tosave.id, tosave.startTime, tosave.endTime, tosave.desc, surfaceSetting.showLifeModel),
    );
    surfaceSetting.maxId++;
    // formValue.value = getNewFormValue();
  } else {
    const temp = timeManageList.getTimeManageById(tosave.id);
    if (temp !== undefined) {
      temp.startTime = tosave.startTime;
      temp.endTime = tosave.endTime;
      temp.desc = tosave.desc;
    }
  }
  // formValue = getNewFormValue();
  surfaceSetting.LifeModelItemsKey = new Date().getTime();
};
const handleValidateClick = (e: MouseEvent) => {
  // console.log('toDealRow',toDealRow);
  e.preventDefault();
  formRef.value?.validate((errors: any) => {
    if (!errors) {
      // message.success("Valid");
      addNewOne();
      modelValue.value.toEdit = false;
    } else {
      console.log(errors);
      // message.error("Invalid");
    }
  });
};
</script>

<style scoped></style>
